import { useEffect, useState } from 'react'
import { getArticles } from '@/api/home'
import { CloseOutline, MoreOutline, SearchOutline } from 'antd-mobile-icons'
import { NavBar, Toast, Popup, Form, DatePicker, Selector, Picker, Button, Dialog } from 'antd-mobile'
import Clist from './list'
import "./index.scss"
import type { getSearchArticlesType } from "@/api/manage/manage"
import userStore from '@/store/userStore'
import { getSearchArticles } from '@/api/manage/manage'
import { FormItem } from 'antd-mobile/es/components/form/form-item'
import dayjs from 'dayjs'
const Manage = () => {
  const { channelList, toGetChannelList, list, setList } = userStore()
  // const [list, setList] = useState([])
  const [selectList, setSelectList] = useState([]);
  const [visible, setVisible] = useState(false)
  const [pvisible, setpVisible] = useState(false)
  const [value, setValue] = useState<string | undefined>('')
  const [status, setStatus] = useState('');
  const [showSelect, setShowSelect] = useState<any>()
  const [time1visible, time1SetVisible] = useState(false)
  const [time1data, time1Setdata] = useState('')
  const [time2visible, time2SetVisible] = useState(false)
  const [time2data, time2Setdata] = useState('')
  const search = () => {

    setVisible(true)

  }

  const now = new Date()
  const yesterday = dayjs().subtract(1, 'day').toDate()


  const toGetList = async () => {
    let result = await getArticles({})
    if (result && result.status == 200) {
      setList(result.data.data.results)
    } else {
      Toast.show({
        icon: 'fail',
        content: '获取文章失败！',
      })
    }
  }

  useEffect(() => {
    setSelectList(channelList.map(item => { return { label: item.name, value: item.id } }))
    toGetList()
    toGetChannelList()
  }, [])


  const onSubmit = async () => {
    const data: getSearchArticlesType = {
      ...(status && { status }), //...可以在不为空时才添加
      ...(value && { channel_id: value }),
      ...(time1data && { begin_pubdate: dayjs(time1data).format('YYYY-MM-DD') }),
      ...(time2data && { end_pubdate: dayjs(time2data).format('YYYY-MM-DD') })
    }
    let result = await getSearchArticles(data);
    if (result && result.status == 200) {
      setList(result.data.data.results)

      setVisible(false)
      setValue('')
      time1Setdata('')
      time2Setdata('')
      setShowSelect('')
    } else {
      Toast.show({
        icon: 'fail',
        content: '搜索文章失败！',
      })
    }
  }

  const del = (data: any) => {
    setList(data)
  }

  return (
    <>
      <NavBar className='top' backIcon={<SearchOutline />} onBack={() => search()}>
        查看文章
      </NavBar>

      <Popup
        visible={visible}
        onMaskClick={() => {

          setVisible(false)
          setValue('')
          time1Setdata('')
          time2Setdata('')
          setShowSelect('')
        }}
        maskStyle={{ background: "rgba(70,70,70,0.2)" }}
        bodyStyle={{
          borderTopLeftRadius: '8px',
          borderTopRightRadius: '8px',
          minHeight: '85vh',
        }}
      >
        <Form
          footer={
            <Button block color='primary' onClick={() => onSubmit()} size='large'>
              提交
            </Button>
          }
        >
          <FormItem name='status' label='状态'>
            <Selector
              style={{
                '--border-radius': '100px',
                '--border': 'solid transparent 1px',
                '--checked-border': 'solid var(--adm-color-primary) 1px',
                '--padding': '8px 24px',
              }}
              showCheckMark={false}
              options={options}
              defaultValue={[status]}
              onChange={(e) => setStatus(e[0])}
            />
          </FormItem>
          <FormItem label='频道' name="channel_id">
            <div style={{ display: 'inline-flex' }}>
              <Button
                onClick={() => {
                  setpVisible(true)
                }}
                style={{ marginRight: "1rem" }}
              >
                选择
              </Button>
              {showSelect?.id >= 0 && <p style={{ margin: 'auto', fontWeight: '600' }}>选择的频道:{showSelect.name}</p>}
            </div>
            <Picker
              columns={selectList.length ? [selectList] : [[{ value: -1, label: '加载失败' }]]}
              visible={pvisible}
              onClose={() => {
                setpVisible(false)
              }}
              value={[value]}
              onConfirm={(v) => {

                const selectedItem = channelList.find(item => item.id == v[0])

                if (selectedItem) {
                  setShowSelect(selectedItem)
                }
                setValue(v[0])
              }}
            />

          </FormItem>
          <FormItem label='开始时间'>

            <div style={{ display: 'inline-flex' }}>
              <Button
                onClick={() => {
                  time1SetVisible(true)
                }}
                style={{ marginRight: "1rem" }}
              >
                选择
              </Button>
              {time1data && <p style={{ margin: 'auto', fontWeight: '600' }}>开始时间:{dayjs(time1data).format('YYYY年-MM月-DD日')}</p>}
            </div>
            <DatePicker
              visible={time1visible}
              onClose={() => {
                time1SetVisible(false)
              }}
              defaultValue={yesterday}
              max={now}
              onConfirm={val => {
                if (!time2data) {
                  time1Setdata(val.toString())
                } else {
                  let d = new Date(time2data);
                  if (val > d) {
                    Toast.show({
                      icon: 'fail',
                      content: "开始时间不能比结束时间晚",
                    })
                    time1Setdata('')
                  } else {
                    time1Setdata(val.toString())
                  }
                }


              }
              }
            >

            </DatePicker>

          </FormItem>

          <FormItem label='结束时间'>
            <div style={{ display: 'inline-flex' }}>
              <Button
                onClick={() => {
                  time2SetVisible(true)
                }}
                style={{ marginRight: "1rem" }}
              >
                选择
              </Button>
              {time2data && <p style={{ margin: 'auto', fontWeight: '600' }}>结束时间:{dayjs(time2data).format('YYYY年-MM月-DD日')}</p>}
            </div>
            <DatePicker
              visible={time2visible}
              onClose={() => {
                time2SetVisible(false)
              }}
              defaultValue={now}
              max={now}
              onConfirm={val => {
                if (!time1data) {
                  time2Setdata(val.toString())
                } else {
                  let d = new Date(time1data);
                  if (val < d) {
                    Toast.show({
                      icon: 'fail',
                      content: "结束时间不能比开始时间早",
                    })
                    time2Setdata('')
                  } else {
                    time2Setdata(val.toString())
                  }
                }


              }}
            >

            </DatePicker>

          </FormItem>
        </Form>
      </Popup>

      <Clist></Clist>
    </>
  )
}


export default Manage

const options = [
  {
    label: '全部',
    value: '',
  },
  {
    label: '草稿',
    value: '1',
  },
  {
    label: '审核通过',
    value: '2',
  },
]
